package com.bangwz.handler;

import java.nio.ByteBuffer;

import org.tio.client.intf.ClientAioHandler;
import org.tio.core.ChannelContext;
import org.tio.core.GroupContext;
import org.tio.core.exception.AioDecodeException;
import org.tio.core.intf.Packet;

import com.bangwz.log.PrintLog;
import com.bangwz.pack.MyPacket;

public class MyClientAIOHander implements ClientAioHandler {

	private static MyPacket heartbeatPacket = new MyPacket();

	@Override
	public Packet decode(ByteBuffer buffer, ChannelContext channelContext) throws AioDecodeException {
		// 读取到的长度
		int readableLength = buffer.limit() - buffer.position();

		// 收到长度不足以达到包头长度，
		if (readableLength < MyPacket.HEAD_LENTH)
			return null;
		// 读取消息体的长度
		int bodyLength = buffer.getInt();

		if (bodyLength < 0)
			throw new AioDecodeException(
					"bodyLength [" + bodyLength + "] is not right, remote:" + channelContext.getClientNode());
		// 计算本次需要的长度
		int neededLength = bodyLength + MyPacket.HEAD_LENTH;

		if (readableLength - neededLength < 0) {
			// 不够消息体长度(剩下的buffe组不了消息体)
			return null;
		} else {
			MyPacket myPacket = new MyPacket();
			if (bodyLength > 0) {
				byte[] dst = new byte[bodyLength];
				buffer.get(dst);
				myPacket.setBody(dst);
			}
			return myPacket;
		}

	}

	@Override
	public ByteBuffer encode(Packet packet, GroupContext groupContext, ChannelContext channelContext) {
		MyPacket myPacket = (MyPacket) packet;
		byte[] body = myPacket.getBody();
		int bodyLength = 0;
		if (body != null) {
			bodyLength = body.length;
		}
		int allLength = MyPacket.HEAD_LENTH + bodyLength;
		ByteBuffer byteBuffer = ByteBuffer.allocate(allLength);
		// 设置字节流
		byteBuffer.order(groupContext.getByteOrder());
		byteBuffer.putInt(bodyLength);
		// 写入消息体
		if (body != null) {
			byteBuffer.put(body);
		}
		return byteBuffer;
	}

	@Override
	public void handler(Packet packet, ChannelContext channelContext) throws Exception {
		MyPacket myPacket = (MyPacket) packet;
		byte[] body = myPacket.getBody();
		if (null != body) {
			String string = new String(body, MyPacket.CHARSET);
			PrintLog.log("客户端收到服务器消息:" + string);
		}
	}

	// heart packet
	@Override
	public Packet heartbeatPacket() {
		return heartbeatPacket;
	}

}
